import re

from mongoengine import Document,connect,DynamicDocument,EmbeddedDocument
from mongoengine.fields import IntField,StringField,EnumField,EmbeddedDocumentField,ListField
from enum import Enum
from mongoengine.errors import ValidationError


# 连接到数据库
# connect('test')
connect(
    db='test',          # 数据库名
    host='localhost',      # 主机地址
    port=27017             # 端口号
)
print("scool_models打印输出")

def phone_required(value):
    pattern = r'^1[0-9]{10}$'
    if not re.search(pattern,value):
        raise ValidationError('请输入手机号码')

class SexChoices(Enum):
    MEN = '男'
    WOMEN = '女'

class CourseGrade(EmbeddedDocument):
    # 成绩信息（科目、老师、成绩） -被嵌套的文档
    course_name = StringField(max_length=64,required=True,verbose_name='课程名称')
    teacher = StringField(max_length=16,verbose_name='老师')
    score = IntField(required=True,min_value=0,max_value=100,verbose_name='分数')

# 如果我们想增加一些students没有的字段，可以用DynamicDocument。
# 使用Document如果字段没有定义, 就不能增删改查。可以用DynamicDocument改进
# class Student(Document):
class Student(DynamicDocument):
    # 学生信息
    stu_no = IntField(required=True,unique=True,verbose_name='学号')
    stu_name = StringField(required=True,max_length=16,verbose_name='姓名')
    # sex = StringField(max_length=2,verbose_name='性别',choices=[SexChoices.MEN,SexChoices.WOMEN])
    sex = EnumField(enum=SexChoices,verbose_name='性别')
    class_name = StringField(max_length=10,verbose_name='班级')
    address = StringField(max_length=255, verbose_name='家庭住址')
    phone_no = StringField(max_length=11,validation=phone_required, verbose_name='电话号码')
    age = IntField(min_value=0,max_value=150,verbose_name='年龄')

    grades = ListField(EmbeddedDocumentField(CourseGrade),verbose_name='成绩列表')

    meta = {
        # 指定集合
        # "collection": "students1",
        "collection":"students", #数据库如果没有集合  新增的时候会创建集合并添加数据  如果有集合 新增的时候直接添加数据
        # 排序规则：年龄倒序
        "ordering":['-age','+stu_no']
    }

    def __str__(self):
        return f"{self.stu_no} : {self.stu_name} , {self.class_name}"




class StudentGrade(DynamicDocument):
    # 学生成绩
    stu_no = IntField(required=True,unique=True,verbose_name='学号')
    stu_name = StringField(required=True,max_length=16,verbose_name='姓名')
    # sex = StringField(max_length=2,verbose_name='性别',choices=[SexChoices.MEN,SexChoices.WOMEN])
    sex = EnumField(enum=SexChoices,verbose_name='性别')
    class_name = StringField(max_length=10,verbose_name='班级')
    address = StringField(max_length=255, verbose_name='家庭住址')
    phone_no = StringField(max_length=10, verbose_name='电话号码')
    age = IntField(min_value=0,max_value=150,verbose_name='年龄')

    grade = EmbeddedDocumentField(CourseGrade,verbose_name='成绩列表')

    meta = {
        # 指定集合
        "collection":"grades",
        # 排序规则：年龄倒序
        "ordering":['-age']
    }


